package vn.csc.javafresher.xml.finalassignment.servlet;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import vn.csc.javafresher.xml.finalassignment.service.XMLService;

public class AddGuestServlet extends HttpServlet {
	private static final long serialVersionUID = -7335683767998638092L;
	private static String CONTEXT_PATH = "";
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		CONTEXT_PATH = config.getServletContext().getRealPath("").toString();
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String email = request.getParameter("email");
		String name = request.getParameter("name");
		String subscribe = request.getParameter("subscribe");
		XMLService xmlService = new XMLService(new File(CONTEXT_PATH + "\\WEB-INF\\guest.xml"));
		ArrayList<String> emailList = xmlService.getAllEmail();
		if(xmlService.isRegistered(email, emailList)) {
			response.sendRedirect("error.jsp");
		} else {
			if(xmlService.insertNewItem(name, email, subscribe)) {
				response.sendRedirect("success.jsp");
			}
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
}
